import { Component, OnInit, Input, ChangeDetectorRef, ChangeDetectionStrategy } from "@angular/core";
import { DistrictService } from "../../models/services/district.service";
import { UserDto } from "../../../shared/models/dto/user.dto";
import { BillDto } from "../../../shared/models/dto/bill.dto";
import { CurdService } from "../../../shared/models/services/curd.service";
import { ElectricityMeterDto } from "../../models/dto/electricity-meter.dto";
import * as _ from 'lodash';
import { UtilsService } from "../../services/utils.services";
import { UserCharacteristicRelationshipDto } from "../../models/dto/user-characteristic-relationship.dto";
import { UserFeatureDto } from "../../models/dto/user-feature.dto";
import { SyncUtilService } from "../../services/offline/sync.util.service";
import { SecureStorageService } from "../../services/secure-storage.services";
import { UserCharacteristicRelationship } from "../../models/transform/user-characteristic-relationship";
import { UserFeature } from "../../models/transform/user-feature";
import {Network} from "@ionic-native/network";
import {NetStatus, SyncPushService} from "../../services/offline/sync-push.service";
import {Observable} from "rxjs/Observable";
import { Device } from "@ionic-native/device";

@Component({
  selector: 'arrears-pay-list-component',
  templateUrl: './arrears-pay-list.component.html',
})


export class ArrearsPayListComponent {

  // tslint:disable-next-line:no-input-rename
  @Input('UserId') userNo: any;
  UserObj: any;
  billList: {
    arrears: Array<BillDto>,
    payments: Array<BillDto>,
  } = {
      arrears: [],
      payments: []
    };

  isTotal = [true, true, true, true, true, true, true, true, true, true, true, true];
  isRead = [true, true, true, true, true, true, true, true, true, true, true, true];
  isMore = [true, true, true, true, true, true];
  userInfo: any;
  areaName: string;
  loginAccount: string;
  electricityList: Array<ElectricityMeterDto>;
  billId: string;
  features = [];
  allFeatures: Array<UserFeature> = [];
  featureList = [];
  isElse: boolean = true;
  userFeature: any;
  constructor(
    public districtService: DistrictService,
    public ref: ChangeDetectorRef,
    public device: Device,
    public curdService: CurdService,
    public utils: UtilsService,
    private syncPushService: SyncPushService,
    private network: Network,
    private syncUtilService: SyncUtilService,
    private storage: SecureStorageService,
  ) {
    // TODO
    this.storage.get('loginAccount').subscribe( (res) => {
      this.loginAccount = res;
    });

  }

  ngOnInit(): void {
    this.getData();
    this.getFeature();
  }

  seeArrearsTotal(index) {
    for (let i = 0; i < index; i++) {
      this.isTotal.push(true);
      this.isRead.push(true);
    }
    this.isTotal[index] = !this.isTotal[index];
    this.isRead[index] = true;
  }

  seeReadInfo(index) {
    for (let i = 0; i < index; i++) {
      this.isTotal.push(true);
      this.isRead.push(true);
    }
    this.isRead[index] = !this.isRead[index];
    this.isTotal[index] = true;
  }

  seeMore(index) {
    for (let i = 0; i < index; i++) {
      this.isMore.push(true);
    }
    this.isMore[index] = !this.isMore[index];
  }

  getData() {
    this.curdService.fetchByCondition(UserDto, { and: { id: this.userNo } }).then((res) => {
      let result = Array.from(res["results"])[0];
      this.UserObj = result;
      this.districtService.fetchByDistrictId(this.UserObj.districtId).subscribe((resDistrict) => {
        if (resDistrict) {
          this.areaName = resDistrict.name;
        }
      });
      this.curdService.fetchByCondition(BillDto, { and: { userId: this.UserObj.id } }).then((data) => {
        let resList = data["results"];
        console.log(resList);
        for (let i = 0; i < resList.length; i++) {
          if (resList[i].isSettle === 0) {
            let arrears = resList[i];
            this.billId = resList[i].id;
            this.curdService.fetchByCondition(ElectricityMeterDto, { and: { billId: this.billId } }).then((electricityData) => {
              this.electricityList = electricityData["results"];
              arrears['electricityList'] = this.electricityList;
              this.billList.arrears.push(arrears);
              console.log(JSON.stringify(this.billList.arrears));
            });

          } else {
            let payments = resList[i];
            this.billList.payments.push(payments);
            /// this.billList = this.billList;
          }
        }

        //   this.billList.arrears.forEach((item, index) => {
        //     this.chargeLevel = item.chargeLevel;
        //     this.chargeTimesOne = item.chargeTimesOne;
        //     this.chargeTimesTwo = item.chargeTimesTwo;
        //     this.chargeTimesThree = item.chargeTimesThree;
        //     this.noticeID = item.noticeID;
        //     this.isSettle = item.isSettle;
        //     this.noticeTime = item.noticeUploadTime;
        //     this.attachmentId = item.attachmentId;
        //     this.ThrumnailId = item.ThrumnailId;
        //     // this.chargeAmount = item.chargeAmount;
        //     if (index === 0 ) {
        //       this.chargemonth = item.month;
        //     }
        //     if (index > 1) {
        //       this.chargemonthList.push(item.month);
        //     }

      });


      //   if (this.chargeLevel === 3) {
      //     this.curdService.fetchByCondition(WorkOrderDto, {and: {userId: this.userId}}).then((elem) => {
      //       let resData = elem["results"][0];
      //       this.workOrderID = resData.id;
      //       this.type = resData.type;
      //       this.workOrderStatus = resData.workOrderStatus;
      //       this.workDate = resData;
      //     } );
      //   }
      // });
    });

  }

  getFeature() {
    this.featureList = [];
    this.curdService.fetchByCondition(UserCharacteristicRelationshipDto, {and: {customerNo: this.userNo}}).then( (res) => {
      this.features = Array.from(res["results"]);
      console.log("用户特征有无数据", this.features);

      // if (resData && resData.length > 0) {
      //   for (let i = 0; i < resData.length; i++ ) {
      //     this.featureList.push({markNo: resData[i].markNo, markName: resData[i].markName,
      //        markCount: resData[i].markCount, markUserAccount: resData[i].markUserAccount});
      //   }
      // }
      // console.log("用户数据", this.featureList);
    });
    this.curdService.fetchByCondition(UserFeatureDto).then( (res) => {
      this.allFeatures = Array.from(res["results"]);
      if (this.allFeatures && this.allFeatures.length > 0) {
        this.allFeatures.forEach((item) => {
          this.featureList.push({id: item.markNo, value: item.markName});
        });
      }
    });
  }

  selectUserFeature() {
    let obj = {
        selectedIndex: _.findIndex(this.featureList, (o) => {
          return o.value === this.featureList;
        }) || 0,
        name: 'feature',
        options: this.featureList
    };

    let selectType = (data) => {
        let feature = data.feature.value;
        this.getUserFeature(feature);
    };
    this.utils.popPicker([obj], 'feature', selectType);
  }

  getUserFeature(feature) {
    let listIndex = [];
    this.userFeature = {
      customerNo: null,
      markNo: null,
      markName: null,
      markCount: null,
      markTypeName: null,
      markUserAccount: null,
      syncStatus: 0
    };
    this.featureList.forEach((list) => {
      if (list.value === feature) {
        let id = list.id;
        if (this.features && this.features.length > 0) {
          this.features.forEach((item , index) => {
            listIndex.push(item.markNo);
            if (id === item.markNo) {
              if (this.loginAccount === item.markUserAccount) {
                this.features[index].markCount = item.markCount + 1;
                this.updateData(this.features[index], item.markNo)
                  .subscribe(() => {
                    this.ref.detectChanges();
                  });
              } else {
                this.userFeature.customerNo = this.features[index].customerNo,
                this.userFeature.markNo =  this.features[index].markNo,
                this.userFeature.markName = this.features[index].markName,
                this.userFeature.markCount = 1,
                this.userFeature.markTypeName = null,
                this.userFeature.markUserAccount = this.loginAccount,
                this.userFeature.syncStatus = 0,

                this.addData(this.userFeature)
                  .subscribe(() => {
                    this.features.push(this.userFeature);
                    this.ref.detectChanges();
                  });
              }
            }
          });
          if (listIndex.indexOf(id) === -1) {
            this.userFeature.customerNo = this.userNo,
            this.userFeature.markNo =  list.id,
            this.userFeature.markName = list.value,
            this.userFeature.markCount = 1,
            this.userFeature.markTypeName = null,
            this.userFeature.markUserAccount = this.loginAccount,
            this.userFeature.syncStatus = 0,
            this.addData(this.userFeature)
              .subscribe(() => {
                this.features.push(this.userFeature);
                this.ref.detectChanges();
            });
          }
        } else {
          let data = {
            customerNo: this.userNo,
            markNo: list.id,
            markName: list.value,
            markCount: 1,
            markTypeName: null,
            markUserAccount: this.loginAccount,
            syncStatus: 0,
            hasMappingError: null
          };

          this.addData(data)
            .subscribe(() => {
              this.features.push(data);
              this.ref.detectChanges();
            });
        }
      }
    });

  }


  addData(userCharacteristicRelation) {
    return Observable.fromPromise(this.curdService.addRow(
      { dto: UserCharacteristicRelationshipDto , mapObj: UserCharacteristicRelationship}, userCharacteristicRelation))
      .flatMap(() => {
        if (new RegExp(this.network.type).test(NetStatus.work) || !this.device.cordova) {
          return this.syncPushService.userFeaturePush();
        } else {
          return Observable.of(false);
        }
    });
  }

  updateData(userCharacteristicRelation, num) {
    return this.curdService.updateRow(
      this.syncUtilService.toObjectDto(userCharacteristicRelation, UserCharacteristicRelationshipDto),
    {customerNo: this.userNo, markNo: num})
      .flatMap(() => {
        if (new RegExp(this.network.type).test(NetStatus.work)) {
          return this.syncPushService.userFeaturePush();
        } else {
          return Observable.of(false);
        }
      });
  }
}
